<template>
    <div>
        <yh-dialog drag title="数据源设置" :visible.sync="visibleTemp" width="600px" @close="closeModal" :close-on-click-modal="false">
            <div class="datasource-main">
                <span v-show="!configs.length" style="font-weight:700;color:#ff0000">没有配置任何数据源</span>
                <div v-if="configs.length">
                    <div style="font-weight:550,margin:6px 0 4px 0" :style="{ display: !isEmpty(oldDataSourceCfg) ? '' : 'none' }">
                        原数据源配置:{{ oldDataSourceCfg }}
                    </div>
                    <el-row>
                        <!-- 第一列 -->
                        <el-col :span="4">
                            <el-radio-group v-model="dataType" @change="changeDataType">
                                <el-radio
                                    :label="config.dataType"
                                    v-for="config in configs"
                                    style="display: block;margin-top: 10px;"
                                    :key="config.dataType"
                                >
                                    {{ config.dataName }}
                                </el-radio>
                            </el-radio-group>
                        </el-col>
                        <!-- 第二列 -->
                        <el-col :span="16" style="border-left:1px solid #ccc;padding-left:6px">
                            <el-checkbox-group v-if="children && children.mustInputs && children.mustInputs.length" v-model="mustInputsTemp">
                                <el-checkbox
                                    v-for="child in children.mustInputs"
                                    :label="child.dataName"
                                    @click.native="clickType2(child)"
                                    :key="child.dataName"
                                    disabled
                                >
                                    {{ child.dataName }}
                                    <span style="color: red"> *</span>
                                </el-checkbox>
                            </el-checkbox-group>
                            <el-checkbox-group v-if="children && children.chooseInputs && children.chooseInputs.length" v-model="chooseInputsTemp">
                                <el-checkbox
                                    v-for="child in children.chooseInputs"
                                    :label="child.dataName"
                                    @click.native="clickType2(child)"
                                    :key="child.dataName"
                                >
                                    {{ child.dataName }}
                                </el-checkbox>
                            </el-checkbox-group>
                            <el-checkbox-group
                                v-if="children && children.mutexMustInputs && children.mutexMustInputs.length"
                                v-model="mutexMustInputsTemp"
                            >
                                <el-checkbox
                                    v-for="child in children.mutexMustInputs"
                                    :label="child.dataName"
                                    @click.native="clickType2(child)"
                                    :key="child.dataName"
                                    disabled
                                >
                                    {{ child.dataName }}
                                    <span style="color: red"> *</span>
                                </el-checkbox>
                            </el-checkbox-group>
                            <el-checkbox-group
                                v-if="children && children.mutexChooseInputs && children.mutexChooseInputs.length"
                                v-model="mutexChooseInputsTemp"
                            >
                                <el-checkbox
                                    v-for="child in children.mutexChooseInputs"
                                    :label="child.dataName"
                                    @click.native="clickType2(child)"
                                    :key="child.dataName"
                                >
                                    {{ child.dataName }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-col>

                        <!-- 第三列 -->
                        <el-col :span="4" style="border-left:1px solid #ccc;padding-left:6px">
                            <el-checkbox-group v-if="thirdList && thirdList.relations && thirdList.relations.length" v-model="thirdRelationsTemp">
                                <el-checkbox v-for="rel in thirdList.relations" :label="rel" :key="rel" disabled>
                                    {{ rel }}
                                </el-checkbox>
                            </el-checkbox-group>
                            <el-radio-group v-model="thirdMutex" v-if="thirdList && thirdList.mutex && thirdList.mutex.length">
                                <el-radio v-for="tdm in thirdList.mutex" :label="tdm" :key="tdm">
                                    {{ tdm }}
                                </el-radio>
                            </el-radio-group>
                        </el-col>
                    </el-row>
                </div>
                <div :style="{ display: getChoiceTable() ? '' : 'none' }">你的选择是:{{ getChoiceTable() }}</div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="closeModal">取 消</el-button>
                <el-button size="mini" type="primary" @click="onSubmit">确 定</el-button>
            </div>
        </yh-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Emit, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import { exportFactorToSql, getDataSourceByCodes, updateDatasourceByCodes } from '@/pages/quota/api';

@Component({ name: 'CalculateFactorDatasource' })
export default class CalculateFactorDatasource extends Vue {
    @PropSync('visible') syncVisible: boolean;
    @Prop({ default: '' }) code: string;

    private visibleTemp = false;
    private common = {
        dataType: { '3': 'caihui', '7': 'wande', '1': 'juyuan', '2': 'hengsheng' },
        dataColumns: [],
        showdataType: { '3': '财汇', '1': '聚源', '7': '万得', '2': '恒生' },
        relationType: { mustInputs: '0', chooseInputs: '1', mutexMustInputs: '2', mutexChooseInputs: '3' },
        relationType1: { '0': 'mustInputsChoose', '1': 'chooseInputs', '2': 'mutexMustInputs', '3': 'mutexChooseInputs' },
        inputs: ['chooseInputs', 'mustInputs', 'mutexChooseInputs', 'mutexMustInputs'],
    };
    // 全部数据
    private configs = [];

    // 原数据源配置
    private oldDataSourceCfg: string = '';

    private choiceTableMustInputs: any = {}; // 你的选择是

    private choiceTableChooseInputs: any = {}; // 你的选择是

    // 第二列数据
    private children = {
        dataName: '',
        dataType: '',
        mustInputs: [],
        chooseInputs: [],
        mutexMustInputs: [],
        mutexChooseInputs: [],
    };

    // 第三列数据
    private thirdList = {
        choose: false,
        mutex: [],
        relations: [],
    };

    private dataType = '';

    private mustInputsTemp = [];

    private chooseInputsTemp = [];

    private mutexChooseInputsTemp = '';

    private mutexMustInputsTemp = '';

    private thirdRelationsTemp = [];

    private thirdMutex = '';

    @Watch('visible')
    onWatchVisible(value) {
        if (value && value !== this.visibleTemp) {
            this.visibleTemp = value;
            getDataSourceByCodes(1, [this.code]).then((result: any) => {
                // result = {
                //     codes: ['YH146'],
                //     configs: [
                //         {
                //             chooseInputs: [],
                //             dataType: '2',
                //             mustInputs: ['TFUNDINFO'],
                //             mutexChooseInputs: [],
                //             mutexMustInputs: [],
                //             relations: {},
                //         },
                //         {
                //             chooseInputs: ['TQ_PF_BASICINFO'],
                //             dataType: '3',
                //             mustInputs: ['', '\nOFPROFILE', 'CFPROFILE', '\nSYMBOL_COMP', 'TQ_BD_NEWESTBASICINFO', 'BONDDT', 'SECURITYCODE'],
                //             mutexChooseInputs: [],
                //             mutexMustInputs: [],
                //             oldDataSourceCfg:
                //                 '\nOFPROFILE:SECURITYCODE;CFPROFILE;\nSYMBOL_COMP:SECURITYCODE;TQ_BD_NEWESTBASICINFO;BONDDT:ITPROFILE;SECURITYCODE;TQ_PF_BASICINFO;',
                //             relations: {
                //                 '\nSYMBOL_COMP:0': {
                //                     choose: true,
                //                     mutex: [],
                //                     relations: ['SECURITYCODE'],
                //                 },
                //                 'BONDDT:0': {
                //                     choose: true,
                //                     mutex: [],
                //                     relations: ['ITPROFILE'],
                //                 },
                //                 '\nOFPROFILE:0': {
                //                     choose: true,
                //                     mutex: [],
                //                     relations: ['SECURITYCODE'],
                //                 },
                //             },
                //         },
                //     ],
                // };
                let configs = result.configs;

                let configsData = [];
                const data = configs.map(configItem => {
                    const config: any = {
                        dataType: configItem.dataType,
                        dataName: this.common.showdataType[configItem.dataType],
                    };
                    const relations = configItem.relations;
                    const mustInputs = configItem.mustInputs
                        .filter(item => item !== '')
                        .map(inputName => {
                            const name = inputName + ':0';
                            const relationsItem = relations[name];
                            this.mustInputsTemp.push(inputName);
                            this.choiceTableMustInputs[configItem.dataType] = this.choiceTableMustInputs[configItem.dataType]
                                ? this.choiceTableMustInputs[configItem.dataType]
                                : '';
                            this.choiceTableMustInputs[configItem.dataType] += relationsItem
                                ? inputName + ':' + relationsItem.relations.join(',') + ';'
                                : inputName + ';';

                            if (relationsItem) {
                                return { dataName: inputName, relations: relationsItem };
                            } else {
                                return { dataName: inputName, relations: null };
                            }
                        });
                    const chooseInputs = configItem.chooseInputs
                        .filter(item => item !== '')
                        .map(inputName => {
                            const name = inputName + ':1';
                            const relationsItem = relations[name];
                            // this.chooseInputsTemp.push(inputName);

                            if (relationsItem) {
                                return { dataName: inputName, relations: relationsItem };
                            } else {
                                return { dataName: inputName, relations: null };
                            }
                        });
                    const mutexMustInputs = configItem.mutexMustInputs
                        .filter(item => item !== '')
                        .map(inputName => {
                            const name = inputName + ':2';
                            const relationsItem = relations[name];
                            if (relationsItem) {
                                return { dataName: inputName, relations: relationsItem };
                            } else {
                                return { dataName: inputName, relations: null };
                            }
                        });
                    const mutexChooseInputs = configItem.mutexChooseInputs
                        .filter(item => item !== '')
                        .map(inputName => {
                            const name = inputName + ':3';
                            const relationsItem = relations[name];
                            if (relationsItem) {
                                return { dataName: inputName, relations: relationsItem };
                            } else {
                                return { dataName: inputName, relations: null };
                            }
                        });
                    config.mustInputs = mustInputs;
                    config.chooseInputs = chooseInputs;
                    config.mutexMustInputs = mutexMustInputs;
                    config.mutexChooseInputs = mutexChooseInputs;
                    config.oldDataSourceCfg = configItem.oldDataSourceCfg;
                    return config;
                });
                this.configs = data;
                if (data[0]) {
                    this.$set(this, 'children', data[0]);
                    this.dataType = data[0].dataType;
                    this.oldDataSourceCfg = data[0].oldDataSourceCfg;
                } else {
                    this.$set(this, 'children', {
                        dataName: '',
                        dataType: '',
                        mustInputs: [],
                        chooseInputs: [],
                        mutexMustInputs: [],
                        mutexChooseInputs: [],
                    });
                    this.dataType = '';
                }
            });
        }
    }

    @Watch('chooseInputsTemp')
    watchChooseInputsTemp(curValue) {
        this.choiceTableChooseInputs[this.dataType] = '';
        curValue.forEach(inputName => {
            const name = inputName + ':2';
            const relationsItem = this.children.mustInputs.find(item => item.dataName == name);
            this.choiceTableChooseInputs[this.dataType] +=
                (relationsItem ? inputName + ':' + relationsItem.relations.join(',') + ';' : inputName) + ';';
        });
        // let key = '';
        // if (curValue.length > oldValue.length) {
        //     key = oldValue.find(item => !curValue.includes(item));
        // } else {
        //     key = oldValue.find(item => !curValue.includes(item));
        // }
        // console.log(key);
    }

    // 修改第一列
    changeDataType(value) {
        this.configs.forEach(item => {
            if (item.dataType === value) {
                this.$set(this, 'children', item);
                this.dataType = item.dataType;
                this.oldDataSourceCfg = item.oldDataSourceCfg;
                this.thirdRelationsTemp = []; //
                this.thirdList = {
                    choose: false,
                    mutex: [],
                    relations: [],
                };
            }
        });
    }

    // 点击第二列，显示第三列
    clickType2(child) {
        this.$set(
            this,
            'thirdList',
            child.relations || {
                choose: false,
                mutex: [],
                relations: [],
            }
        );
        this.thirdRelationsTemp = this.thirdList.relations;
    }

    // 关闭弹窗
    closeModal() {
        this.syncVisible = false;
        this.visibleTemp = false;
    }

    onSubmit() {
        // const data = {
        //     codes: this.list.map(item => item.key),
        // };
        if (this.configs.length == 0) {
            this.closeModal();
            return;
        }
        updateDatasourceByCodes({
            chooseInputs: this.choiceTableChooseInputs[this.dataType],
            mustInputs: this.choiceTableMustInputs[this.dataType],
            mutexChooseInputs: '',
            mutexMustInputs: '',
            sourceType: this.dataType,
            type: 1,
            updateCodes: [this.code],
        })
            .then((res: any) => {
                this.closeModal();
                this.$emit('on-submit');
            })
            .catch(e => {
                this.closeModal();
            });
    }

    private getChoiceTable() {
        let value = '';
        if (this.choiceTableMustInputs[this.dataType]) {
            value += this.choiceTableMustInputs[this.dataType];
        }
        if (this.choiceTableChooseInputs[this.dataType]) {
            value += this.choiceTableChooseInputs[this.dataType];
        }
        return value;
    }

    /**
     * 判断为空
     * @param {*判断为空} obj
     */
    isEmpty(obj) {
        return typeof obj == 'undefined' || obj == null || obj === '' || obj.length === 0 || obj === JSON.stringify({});
    }
}
</script>
<style lang="scss" scoped>
.el-col-16 .el-checkbox {
    height: 30px !important;
    display: block;
}
</style>
